package demo.thread;

public class DemoSynThread implements Runnable {

	MyNumber count = new MyNumber();

	public static Integer countI = new Integer(0);

	public static void main(String[] args) throws Exception {
		DemoSynThread dst = new DemoSynThread();
		Runnable r1 = new Count(dst.count, "asd");
		Runnable r2 = new Count(dst.count, "zxc");
		Thread th1 = new Thread(r1);
		Thread th2 = new Thread(r2);
		th1.start();
		th2.start();
		th1.join();
		th2.join();
		System.out.println(dst.count.k);
//
//		Runnable ri1 = new Count("Integer asd");
//		Runnable ri2 = new Count("Integer zxc");
//		Thread thi1 = new Thread(ri1);
//		Thread thi2 = new Thread(ri2);
//		thi1.start();
//		thi2.start();
//		thi1.join();
//		thi2.join();
//		System.out.println(countI);

	}

	@Override
	public void run() {

	}

}

class Count implements Runnable {
	private MyNumber count;
	private Integer countI = null;
	String name;

	@Override
	public void run() {
		if (count != null)
			synchronized (count) {
				for (int i = 0; i < 5; i++) {
					tang();
				}
			}

		if (DemoSynThread.countI != null)
			synchronized (DemoSynThread.countI) {
				for (int i = 0; i < 5; i++) {
					tang();
				}
			}
	}

	public Count(MyNumber count, String name) {
		this.count = count;
		this.name = name;
	}

	public Count(Integer count, String name) {
		this.countI = count;
		this.name = name;
	}
	
	public Count(String name) {
		this.name = name;
	}

	public void tang() {
		if (count != null) {
			count.k += 1;
			System.out.println(name + ": " + count.k);
		}

		if (DemoSynThread.countI != null) {
			DemoSynThread.countI += 1;
			System.out.println(name + ": " + DemoSynThread.countI);
		}
	}
}

class MyNumber {
	public int k = 0;
}